package com.lydms.interval;

import com.lydms.service.WordEmailService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@EnableScheduling
public class EmailIterval {

    private final static Logger logger = LogManager.getLogger(EmailIterval.class);

    @Autowired
    private WordEmailService emailService;


//    定时时间1
    @Value(value = "${sendEmailTime1}")
    private boolean send1;
//    定时时间2
    @Value(value = "${sendEmailTime2}")
    private boolean send2;
//  邮箱地址
    @Value(value = "${sendEmail.host}")
    private String email;



    /**
     * 定时时间1，发送邮件
     */
    @Scheduled(cron = "${interval.sendEmail}")
    public void intervalSms1() {
        timeLog();
        if (send1) {
            sendEmail(email);
        }else {
            logger.info("此时间点不发送邮件");
        }
    }


    /**
     * 定时时间2，发送邮件
     */
    @Scheduled(cron = "${interva2.sendEmail}")
    public void intervalSms2() {
        timeLog();
        if (send2) {
            sendEmail(email);
        }
        logger.info("此时间点不发送邮件");
    }



    /**
     * 定时发送 邮件
     * @param email    邮箱号
     */
    private void sendEmail(String email) {
//        获取当天的内容的Html格式文件
        String htmlEmailByDay = emailService.getHtmlEmailByDay(null);

        String[] splitEmail = email.split(",");

        for (String onceEmail : splitEmail) {
            emailService.sendHtmlMail(onceEmail,"定时英语学习",htmlEmailByDay);
        }
    }

    /**
     * 打印当前时间
     */
    private void timeLog() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format1 = format.format(date);
        logger.info(format1 + " 发送邮件，邮件地址为:{}", email);
    }
}
